﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
//using monitor_server_2_WPF.ControlTabs.DeviceListParamPanels;
using monitor_server_2_WPF.DeviceListParamPanels;
using monitor_2_DBwork;
using Image = System.Windows.Controls.Image;
using SystemColors = System.Windows.SystemColors;

namespace monitor_server_2_WPF
{
    /// <summary>
    /// Логика взаимодействия для DeviceListTabControl.xaml
    /// </summary>
    public partial class DeviceListTabControl : Res.IControlForMainWindow
    {
        //public delegate void UpdateRegionTreeNodeDelegate(string regionName);
        public delegate void UpdateRegionTreeNodeDelegate();

        public static UpdateRegionTreeNodeDelegate UpdateRegion;

        private readonly ObservableCollection<TreeViewItem> _deviceTreeItems;

        public DeviceListTabControl()
        {
            InitializeComponent();
            //UpdateRegion = UpdateRegionTreeNode;
            UpdateRegion = UpdateCurrentSelectedRegionTreeNode;
            Item1.Header = Res.Rm.GetString("DeviceList");
            if (_deviceTreeItems == null)
                _deviceTreeItems = new ObservableCollection<TreeViewItem>();
            DeviceTree.ItemsSource = _deviceTreeItems;
            DeviceTree.Background = new SolidColorBrush(Res.LighBlack);
            DeviceTree.Foreground = new SolidColorBrush(Colors.White);
            DeviceTree.ItemContainerStyle = GetTreeViewItemStyle();
            DeviceTree.SelectedItemChanged += DeviceTree_SelectedItemChanged;
            DeviceTree.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));

            ParamPanel.Background = new SolidColorBrush(Res.LighBlack);
            
            //UseLayoutRounding = true;
            UpdateTree();
        }

        void DeviceTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var item = (TreeViewItem)((TreeView) sender).SelectedItem;
            if (item == null)
                return;
            //Updates parameters every time node is changed
            ParamPanel.Children.Clear();
            ParamPanel.Children.Add(GetParamsPanel(item));
        }

        //Choose panel with parameters for node
        private static UIElement GetParamsPanel(FrameworkElement item)
        {
            var additionalInfo = item.Tag;

            if (additionalInfo.GetType() == typeof (DeviceTreeItem.RegionInfo))
            {
                return RegionParamPanel.GetPanel(additionalInfo as DeviceTreeItem.RegionInfo);
            } 

            if (additionalInfo.GetType() == typeof(DeviceTreeItem.StationInfo))
            {
                return StationParamPanel.GetPanel(additionalInfo as DeviceTreeItem.StationInfo);
            }

            if (additionalInfo.GetType() == typeof(DeviceTreeItem.DeviceInfo))
            {
                return DeviceParamPanel.GetPanel(additionalInfo as DeviceTreeItem.DeviceInfo, ((item as TreeViewItem).Parent as TreeViewItem).Header.ToString());
            } 

            return null;
        }

        //Udpate the whole tree
        private void UpdateTree()
        {
            var deviceTree = DBwork.GetDeviceTree();
            _deviceTreeItems.Clear();

            foreach (var oblTreeItem in deviceTree)
            {
                UpdateRegionTreeNode(oblTreeItem);
            }

            ParamPanel.Children.Clear();
        }
        
        //Request to update selected node
        private void UpdateCurrentSelectedRegionTreeNode()
        {
            var item = DeviceTree.SelectedItem as TreeViewItem;
            if (item.Tag is DeviceTreeItem.RegionInfo)
            {
                UpdateRegionTreeNode((item.Tag as DeviceTreeItem.RegionInfo).Region);
            }
            else if (item.Tag is DeviceTreeItem.StationInfo)
            {
                UpdateRegionTreeNode((((TreeViewItem)item.Parent).Tag as DeviceTreeItem.RegionInfo).Region);
            }
            else if (item.Tag is DeviceTreeItem.DeviceInfo)
            {
                UpdateRegionTreeNode((((TreeViewItem)((TreeViewItem)item.Parent).Parent).Tag as DeviceTreeItem.RegionInfo).Region);
            }
        }

        //Request to update node
        private void UpdateRegionTreeNode(string regionName)
        {
            GetNewRegionTreeNode(regionName);
            foreach (TreeViewItem item in DeviceTree.Items)
            {
                if (item.Header.ToString().Equals(regionName))
                {
                    //Менять выбранное устройство
                }
            }
        }

        //Get new node data from db and update tree
        private void GetNewRegionTreeNode(string regionNodeName)
        {
            DeviceTreeItem newItem;
            try
            {
                newItem = DBwork.GetDeviceTreeNode(regionNodeName);
            }
            catch (DeviceTreeItem.RegionNotFoundException)
            {
                return;
            }

            UpdateRegionTreeNode(newItem);
        }

        //Update 1 node
        private void UpdateRegionTreeNode(DeviceTreeItem oblTreeItem)
        {
            if (_deviceTreeItems.Count > 0)
            {
                bool yes = false;
                int i = 0;
                foreach (var deviceTreeItem in _deviceTreeItems)
                {
                    if (oblTreeItem.Header == deviceTreeItem.Header.ToString())
                    {
                        yes = true;
                        break;
                    }
                    i++;
                }
                
                if (i < _deviceTreeItems.Count && yes)
                {
                    _deviceTreeItems.RemoveAt(i);
                }
            }

            //Region
            var oblTreeNode = new TreeViewItem
            {
                Header = new MyDockPanel(MyDockPanel.DeviceTreeNodeHeaderImage.Region , oblTreeItem.Header),
                Tag = oblTreeItem.AdditionalInfo
            };
            if (oblTreeItem.SubItems != null && oblTreeItem.SubItems.Count > 0)
                foreach (var stationTreeItem in oblTreeItem.SubItems)
                {
                    //Station
                    var stationTreeNode = new TreeViewItem
                    {
                        Header = new MyDockPanel(MyDockPanel.DeviceTreeNodeHeaderImage.Station, stationTreeItem.Header),
                        Tag = stationTreeItem.AdditionalInfo
                    };
                    if (stationTreeItem.SubItems != null && stationTreeItem.SubItems.Count > 0)
                        foreach (var deviceTreeItem in stationTreeItem.SubItems)
                        {
                            //Device
                            var deviceTreeNode = new TreeViewItem
                                {
                                    Tag = deviceTreeItem.AdditionalInfo
                                };
                            //Определение активности устройства
                            var im = ((DeviceTreeItem.DeviceInfo) deviceTreeItem.AdditionalInfo).IsActive ? MyDockPanel.DeviceTreeNodeHeaderImage.ActiveDevice : MyDockPanel.DeviceTreeNodeHeaderImage.InactiveDevice;
                            string title  = ((DeviceTreeItem.DeviceInfo)deviceTreeItem.AdditionalInfo).Title;
                            if (string.IsNullOrEmpty(title))
                                title = deviceTreeItem.Header;
                            deviceTreeNode.Header = new MyDockPanel(im, title);
                            stationTreeNode.Items.Add(deviceTreeNode);
                        }
                    oblTreeNode.Items.Add(stationTreeNode);
                }
            _deviceTreeItems.Add(oblTreeNode);
        }

        public UIElement GetControl(out MainWindow.HidingDelegate del)
        {
            del = null;
            //UpdateTree();
            ClearForm();
            foreach (var deviceTreeItem in _deviceTreeItems)
            {
                deviceTreeItem.IsExpanded = false;
            }
            return this;
        }

        //Clear parameters panel
        private void ClearForm()
        {
            ParamPanel.Children.Clear();
        }

        private void DeviceTree_OnExpanded(object sender, RoutedEventArgs e)
        {
            //var oldItem = (TreeViewItem)e.OriginalSource;
            //GetNewRegionTreeNode(oldItem.Header.ToString());
            //foreach (var item in DeviceTree.Items)
            //{
            //    if (ReferenceEquals(((TreeViewItem) item).Header, oldItem.Header.ToString()))
            //    {
            //        ((TreeViewItem) item).IsExpanded = true;
            //        return;
            //    }
            //}

        }

        private Style GetTreeViewItemStyle()
        {
            var s = new Style(typeof (TreeViewItem));
            s.Resources.Add(SystemColors.ControlBrushKey, new SolidColorBrush(Res.NiceBlue));
            s.Resources.Add(SystemColors.HighlightBrushKey, new SolidColorBrush(Res.NiceBlue));

            var t1 = new Trigger { Property = IsMouseOverProperty, Value = true };
            var s1 = new Setter { Property = BackgroundProperty, Value = Res.MouseOverBrush };
            t1.Setters.Add(s1);
            s.Triggers.Add(t1);

            return s;
        }

        private void Item1_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if ((e.MouseDevice.DirectlyOver as TextBlock) == null ||
                (e.MouseDevice.DirectlyOver as TextBlock).Text != Res.Rm.GetString("DeviceList"))
                return;
            UpdateTree();
        }
    }

    

}
